(function () {

    var searchItemTmpl = {
        game : `
    <li class="common-game-item">
        <a class="common-game-avatar" href="{% data.id %}" target="_blank">
            {% if( data.img ){ %}
                <img data-original="{% data.img %}">
            {% }else{ %}
                <img data-original="{% data.game_img %}">
            {% } %}
        </a>
        <div class="common-game-detail">
            <div class="common-game-info">
                <div class="common-game-name">
                    <a class="ellipse" href="{% data.id %}"target="_blank">{% data.name %}</a>
                        {% if( data.is_android ){ %}
                            <span class="iconfont icon-anzhuo"></span>
                        {% } %}
                        {% if( data.is_ios ){ %}
                            <span class="iconfont icon-iOS"></span>
                        {% } %}
                </div>
                
                {% if ( data.cate_id ){ %}
                <!--游戏-->
                <div class="common-game-intro">
                    <div class="game-cate">{% data.cate_id %}</div>
                    <div>{% data.nums %}人关注</div>
                </div>
                    {% if ( data.tags ){ %}
                        <div  class="common-game-additional common-game-tags">
                            {% for(var i = 0; i < data.tags.length; i++ ) { %}
                                <span> {% data.tags[i] %} </span>
                            {% } %}
                        </div>  
                    {% } %}     
                               
                {% }else if( data.intro ){ %}
                <!--礼包-->
                <div class="common-game-intro">
                    <div class="game-intro-text  ellipse">{% data.intro %}</div>
                </div>
                
                <div  class="common-game-additional">
                    <div class="progress-wrapper">
                        <div class="progress-bar">
                            <div class="progress-rate" style="width:{% (data.last_num / data.all_num * 100).toFixed(2)%}%"></div>
                        </div>
                        <span class="progress-num">{% (data.last_num / data.all_num * 100).toFixed(2) %}%</span>
                    </div>
                </div>
                   
                {% }else if( data.money ){ %} 
                <!--首充码 -->
                <div class="common-game-intro" style="color: #666">
                    所属游戏：<span style="color: #000;">{% data.game_name %}</span>
                </div>
                <div  class="common-game-additional">
                    <div style="margin-right: 20px">
                        剩余<span style="color: #FF4545;">{% data.last_num %}</span>个
                    </div>
                    <div class="common-libao-tips">自激活后{% data.valid_day %}日内有效</div>
                </div>
                {% } %}  
            </div>
        </div>
    </li>
    `,

        info : ` <li class="common-info-item">
                  <div class="common-info-wrapper">
                    <a class="common-info-img common-news-img mr-10" href="{% data.id %}" target="_blank">
                      <img data-original="{% data.img %}">
                      {% if(data.video){ %}
                      <span class="iconfont icon-video-tint"></span>
                      {% } %}
                    </a>
                    <div class="common-info-head">
                      <h3 class="common-info-title"><a class="ellipse" href="{% data.id %}" target="_blank">{% data.title %}</a></h3>
                      <div class="common-info-desc">
                       
                        <div class="common-info-time ellipse">
                          <span class="iconfont icon-shijian"></span>
                          {% data.push_time %}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="common-info-intro ellipse">{% data.intro %}</div>
               </li>`
    };

    function main() {
        var keyword = utils.getQueryString('keyword'),
            cate = 'index';

        $('#searchKeyword').text(decodeURI(keyword));
        renderSearchResult( cate, keyword );

        $('.search-cate-item').on('click', function (e) {
            e = e || window.event;
            var cate = $(e.target).attr('data-cate');
            changeActiveClass($(e.target));
            renderSearchResult( cate, keyword );
        })
    }
    
    function changeActiveClass( $target ) {
        var navs = $('.search-cate-item'),
            active = 'search-cate-item-active';
        $.each(navs, function ( index, item ) {
            var $item = $(item),
                className = $item.attr('class').trim();
            if(className.indexOf(active) > -1){
                $item.removeClass(active);
            }
        });

        $target.addClass(active);
    }

    //渲染全部结果
    function renderSearchResult( cate, keyword ) {
        if( keyword ){
            $.ajax({
                type: 'POST',
                url: '/search/ajax_'+ cate +'?keyword=' + keyword,
                dataType: 'json',
                success: function ( res ) {
                    if( res.ret === 0 ) {
                        renderTotalList(keyword, cate, res.data);
                    }else{
                        alert( res.msg );
                    }
                }
            });
        }
    }

    function renderTotalList( keyword, cate, totalData ) {
        var $container = $('.search-panel-container');
        //清空
        $container.empty();

        //初始渲染
        $.each( totalData, function ( key, lists ) {
            var len = key.length,
                type = key.indexOf('_list') > -1 ? key.trim().slice( 0, len - 5 ) : '',
                typeNames = {
                    game: '游戏',
                    libao: '礼包',
                    coupon: '首充码',
                    video: '视频',
                    article: '资讯'
                },
                tmpl = '';


            if(type === 'game' || type === 'libao' || type === 'coupon'){
                tmpl = searchItemTmpl.game;
            }else{
                tmpl = searchItemTmpl.info;
            }

            if( lists.length ){
                $container.append(function () {
                    var html =
                        `<div class="common-panel search-panel">
                            <h1 class="panel-title">
                                ${ typeNames[type] }
                                ${ cate === 'index' ? `<a href="javascript:;" data-cate=${ type } class="more">更多</a>` : '' }
                            </h1>
                            <div class="panel-body">
                                <ul class="common-list" data-list=${type}></ul>
                                ${ cate !== 'index' ? `<div class="common-list-more game-list-more" id="getMoreBtn">点击加载更多..</div>` : '' }
                            </div>
                        </div>`;
                    return html;
                });
                renderCateList({
                    selector : '[data-list="'+ type +'"]',
                    tmpl: tmpl,
                    lists: lists,
                    cate: cate,
                    type: type,
                    keyword: keyword
                });
            }else if( type ){
                $container
                    .append(function () {
                    var html =
                        `<div class="common-panel search-panel">
                            <h1 class="panel-title">${ typeNames[type] }</h1>
                            <div class="panel-body panel-body-visible">
                                <div class="search-none">暂无更多搜索结果</div>
                            </div>
                        </div>`;
                    return html;
                });
            }
        });
    }
    
    function renderCateList( opts ) {
        //配置渲染参数
        var renderDefaultOpts = {
                insertTarget: opts.selector,
                template: opts.tmpl,
                handleFn: {
                    'cate_id': utils.setDataItem.bind(utils),
                    'tags': utils.setDataItem.bind(utils),
                    'push_time': utils.getLocalTime.bind(utils),
                    'type': function ( val ) {
                        var newsCateName = ['资讯', '攻略', '评测', '视频'];
                        return newsCateName[ val - 1 ];
                    },
                    'id': function ( val ) {
                        var itemUrl = '';
                        switch ( opts.type ){
                            case 'game': {
                                itemUrl = '/game/detail/' + val;
                                break;
                            }
                            case 'libao': {
                                itemUrl = '/libao/' + val;
                                break;
                            }
                            case 'coupon': {
                                itemUrl = '/coupon/' + val;
                                break;
                            }
                            default:{
                                itemUrl = '/topic/' + val;
                                break;
                            }
                        }

                        return itemUrl;

                    }
                },
                beforeRender: function ( page ) {
                    if( page === 2 ){
                        //list有值
                        $('.search-panel .panel-body').addClass('panel-body-visible');
                    }
                },
                afterRender: function () {
                    $('img').lazyload({
                        effect: "fadeIn",
                        effectspeed: 1500
                    });
                    var $more = $('.search-panel .more');
                    if( $more.length ){
                        $more
                            .off('click')
                            .on('click', function (e) {
                                e = e || window.event;
                                var cate = $(e.target).attr('data-cate');
                                changeActiveClass($('.search-cate').find('[data-cate='+ cate +']'));
                                renderSearchResult( cate, opts.keyword );
                                $('body,html').animate({ scrollTop: 0 },500,'swing');
                            })

                    }
                }
            },
            renderOpts,
            renderObj;
        if( opts.cate !== 'index' ){
            renderOpts = $.extend(true, {}, renderDefaultOpts, {
                btn: '#getMoreBtn',
                lists: opts.selector,
                listType: opts.type,
                url: '/search/ajax_'+ opts.type +'?keyword=' + opts.keyword,
                page: 1,
                loadingAnim: true,
                loadingAnimDom: '.loading-container',
                initialFirstScreen: true
            });
            renderObj = new LoadData( renderOpts );
        }else{
            renderObj = $( opts.selector ).render( renderDefaultOpts );
            renderObj.reRender( opts.lists, 2 );
        }
    }

    main();
})();